package com.lottery.ruok.lottrey.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.bean.ProclamationModel;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import count_down.CountDownManager;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import utils.Utils;

public class ProclamationDialog extends Dialog {
    private final Context mContext;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    private CountDownManager.CountDownModel countDownModel;
    private ProclamationModel data;
    private boolean isDone;//是否已执行

    public ProclamationDialog(@NonNull Context context) {
        this(context, 0);
    }

    public ProclamationDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        this.mContext = context;
        init();
        initView();
        load();
    }


    private void init() {
        countDownModel = new CountDownManager.CountDownModel() {
            @Override
            public void onExecute() {
                if (data != null) {
                    if (data.getCountDown() <= 0) {
                        return;
                    }
                    data.setCountDown(data.getCountDown() - 1);
                    tvConfirm.setText("查看（" + data.getCountDown() + ")");
                    if (data.getCountDown() <= 0) {
                        if (!isDone) {
                            //没有执行过就执行
                            goWeb();
                        }
                    }
                }
            }
        };
    }

    private void initView() {
        setContentView(R.layout.view_proclamation);
        ButterKnife.bind(this);

    }

    private void load() {
//        String url = String.format("https://lrgrmxx.com/android/yundingcaiba/%s_proclamation.json", BuildConfig.COMPANY_CODE);
//
//        httpProclamation(url);
//        ProclamationModel proclamationModel = new ProclamationModel();
//        proclamationModel.setForce(true);
//        proclamationModel.setCountDown(10);
//        proclamationModel.setContent("各位会员，您好！目前鸿运彩吧网站将在2018年7月26日02:00到2018年7月26日06:00进行优化升级系修改版面，升级版面成功后建议您使用网站flc8.cc 进行登入，同时原有的APP也将停止使用需从新进行下载 ，谢谢您一直以来对我们的支持。");
//        proclamationModel.setTitle("鸿运彩吧更换版面停运公告");
//        proclamationModel.setUrl("http://flc8.cc");
//        proclamationModel.setStopApp(true);
//        setData(proclamationModel);
//        if (!ProclamationDialog.this.isShowing()) {
//            show();
//        }
    }

    /**
     * 请求公告
     */
    private void httpProclamation(String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();

            }

            @Override
            public void onResponse(Call call, final Response response) {
                ((Activity) mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String jsonStr = response.body().string();
                            if (!Utils.isEmpty(jsonStr)) {
                                Gson gson = new Gson();
                                ProclamationModel proclamationModel = gson.fromJson(jsonStr, ProclamationModel.class);
                                setData(proclamationModel);
                                Toast.makeText(mContext, proclamationModel.toString(), Toast.LENGTH_LONG).show();

                                if (proclamationModel != null) {
                                    if (!ProclamationDialog.this.isShowing()) {
                                        show();
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

            }
        });
    }

    private void setData(ProclamationModel data) {
        this.data = data;
        updateView();
    }

    private void updateView() {
        if (data != null) {
            if (data.isForce()) {
                //强制阅读
                setCanceledOnTouchOutside(false);
                setCancelable(false);
                //开始倒计时
                CountDownManager.asInstance().register(countDownModel);
            }
            tvTitle.setText(data.getTitle());
            tvContent.setText(data.getContent());
            tvConfirm.setText("查看");

        }
    }

    @Override
    public void onDetachedFromWindow() {
        CountDownManager.asInstance().unRegister(countDownModel);
        super.onDetachedFromWindow();
    }

    @OnClick(R.id.tv_confirm)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_confirm:
                goWeb();
                break;
        }
    }

    private void goWeb() {
        isDone = true;
        if (data != null && !Utils.isEmpty(data.getUrl())) {
            Utils.openBrowser(data.getUrl(), mContext);
        }
        if (data != null && data.isStopApp()) {
            //不关闭dialog 不让使用app
        } else {
            dismiss();
        }
    }
}
